/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
#include "simplebuffer.h"

namespace gimi {

SimpleBuffer::~SimpleBuffer()
{
  if (buffer != NULL) {
    delete[] buffer;
  }
}

int SimpleBuffer::allocateMoreBuffer(const int additionSize)
{
  //TODO Disabled for now.
  /*
  if (currentAllocatedSize + additionSize > maxAllocatedSize) {
    dPrint(3, "Cannot allocate %d bytes in addition to %d, maximum size reached!",
        currentAllocatedSize, additionSize);
    return GIMI_ERROR;
  } else {
    */
    dPrint(12, "Allocating %d bytes in addition to %d", additionSize, currentAllocatedSize);
    currentAllocatedSize += additionSize;
    char* newBuffer = new char[currentAllocatedSize + additionSize];
    memcpy(newBuffer, buffer, currentSize);
    delete[] buffer;
    buffer = newBuffer;
  
    return GIMI_OK;
  //}
}

int SimpleBuffer::pushData(const char* data,
                           const int dataLength)
{
  if (data == NULL || dataLength < 1) {
    dPrint(6, "Given datapointer was NULL or size was invalid.");
    return GIMI_ERROR;
  }
  
  int requiredBufferSize = currentSize + dataLength;
  
  // Check if we should allocate more space for buffer.
  if (requiredBufferSize > currentAllocatedSize) {
    allocateMoreBuffer(requiredBufferSize - currentAllocatedSize);
  }
  
  // Add the new data.
  memcpy(buffer + currentSize, data, dataLength);
  
  dPrint(12, "Added %d bytes to existing %d in buffer, total is %d", dataLength,
         currentSize, currentSize+dataLength);
  
  currentSize += dataLength;
  
  return GIMI_OK;
}

int SimpleBuffer::shiftBuffer(const int nBytes)
{
  if (nBytes < 1) {
    dPrint(6, "Number of bytes cannot be negative!");
    return GIMI_ERROR;
  }
  
  if (nBytes >= currentSize) {
    dPrint(6, "Size of shift cannot be larger than current size!");
    return GIMI_ERROR;
  }
  
  currentSize -= nBytes;
  
  memmove(buffer, buffer+nBytes, currentSize);
 
  dPrint(12, "Shifted %d bytes from position %d to start of buffer.", currentSize, nBytes);
  
  return GIMI_OK;
}

}; // end namespace gimi
